package com.woniuxy.mapper;

import java.util.List;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import com.woniuxy.pojo.User;

/**
 * 用户mapper
 * 
 * @author YangTao
 *
 */
@CacheNamespace // 开启二级缓存
public interface UserMapper {
    @Select("select * from user")
    public List<User> all();

    @Insert("INSERT INTO user (user_name,user_password,user_phone) VALUES (#{user_name},#{user_password},#{user_phone})")
    public int add(User user);

    // 查询插入的数据的id
    @Select("select @@IDENTITY")
    public int findUser_number();


    @Select("select * from user where user_number=#{user_number}")
    @Results({
			@Result(id = true, column = "user_number", property = "user_number"),
			@Result(column = "user_name", property = "user_name"),
			@Result(column = "user_password", property = "user_password"),
			@Result(column = "user_phone", property = "user_phone"),
			@Result(column = "user_number", property = "roles", many = @Many(

					select = "findRolesByUser_number",
					// 设置懒加载
					fetchType = FetchType.LAZY
			))
    })
	public User findUserByNumber(int user_number);

    // 查询用户权限
	@Select("SELECT role_name FROM user_role INNER JOIN roles "
			+ "WHERE user_role.role_id = roles.role_id  AND user_id = #{user_number}")
    public List<String> findRolesByUser_number(String user_number);

	// 根据权限查用户
	@Select("SELECT * FROM user_role INNER JOIN roles INNER JOIN `user` "
			+ "WHERE user_role.role_id = roles.role_id AND role_name = #{role_name} GROUP BY user_number")
	public List<User> findAllByRole_name(String role_name);

	// 根据id查用户
	@Select("SELECT * FROM user WHERE user_number = #{id}")
	public User findUserById(int id);

	// 根据电话查用户
	@Select("SELECT * FROM `user` WHERE user_phone =#{User_phone}")
	public User findUserByUser_phone(String User_phone);
	
	// 根据电话和姓名查用户id
    @Select("select  IFNULL((SELECT user_number FROM `user` WHERE user_phone =#{0} AND user_name =#{1}) ,0)")
	public int findUser_numberByPhone(String User_phone, String user_name);

	// 通过角色查角色id
	@Select("SELECT role_id FROM roles WHERE role_name = #{role_name}")
	public int findRoles(String rolesName);

	// 插入用户——角色信息
	@Insert("INSERT INTO user_role VALUES (#{0},#{1})")
	public int addUserRole(int user_id, int role_id);
}
